﻿#include<iostream>
using namespace std;


//插入排序

void InsertSort(int* arr, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		int end = i;
		int tem = arr[end + 1];
		while (end >= 0)
		{
			if (tem < arr[end])
			{
				arr[end + 1] = arr[end];
				end--;
			}
			else
			{
				break;
			}
		}
		arr[end + 1] = tem;
	}
}


//希尔排序
void ShellSort(int* arr, int n)
{
	int gap = n;
	while (gap > 1)
	{
		gap /= 2;
		for (int i = 0; i < n - gap; i++)
		{
			int end = i;
			int tem = arr[end + gap];
			while (end >= 0)
			{
				if (tem < arr[end])
				{
					arr[end + gap] = arr[end];
					end -= gap;
				}
				else
				{
					break;
				}
			}
			arr[end + gap] = tem;
		}
	}
}


//选择排序

void swap(int* a, int* b)
{
	int tem = *a;
	*a = *b;
	*b = tem;
}

void SelectSort(int* arr, int n)
{
	int begin = 0;
	int end = n - 1;
	while (begin < end)
	{
		int maxi = begin;
		int mini = begin;

		for (int i = begin; i <= end; i++)
		{
			if (arr[i] < arr[mini])
			{
				mini = i;
			}
			if (arr[i] > arr[maxi])
			{
				maxi = i;
			}
		}

		swap(&arr[mini], &arr[begin]);
		if (begin == maxi)
		{
			maxi = mini;
		}

		swap(&arr[maxi], &arr[end]);
		++begin;
		--end;
	}
}


//冒泡排序
void BubbleSort(int* arr, int n)
{
	int end = n;
	while (end)
	{
		int flag = 0;
		for (int i = 1; i < end; i++)
		{
			if (arr[i - 1] > arr[i])
			{
				int tem = arr[i];
				arr[i] = arr[i - 1];
				arr[i - 1] = tem;
				flag = 1;
			}
		}
		if (flag == 0)
		{
			break;
		}
		--end;
	}
}


//快速排序
void QuickSort(int* arr, int begin, int end)
{
	if(begin >= end)
	{
		return;
	}

	int left = begin;
	int right = end;

	int keyi = begin;
	while (begin < end)
	{
		while (arr[end] >= arr[keyi] && begin < end)
		{
			--end;
		}
		while (arr[begin] <= arr[keyi] && begin < end)
		{
			++begin;
		}

		swap(&arr[begin], &arr[end]);
	}
	swap(&arr[keyi], &arr[end]);
	keyi = end;

	QuickSort(arr, left, keyi - 1);
	QuickSort(arr, keyi + 1, right);
}

//合并排序
void Merge(int* arr, int begin, int mid, int end)
{
	int* B = new int[end - begin + 1];
	int i = begin, j = mid + 1, k = 0;
	while (i <= mid && j <= end)
	{
		if (arr[i] < arr[j])
		{
			B[k++] = arr[i++];
		}
		else
		{
			B[k++] = arr[j++];
		}
	}
	while (i <= mid)
	{
		B[k++] = arr[i++];
	}
	while (j <= end)
	{
		B[k++] = arr[j++];
	}
	for (i = begin, k = 0; i <= end; i++)
	{
		arr[i] = B[k++];
	}
	delete[] B;
}

void MergeSort(int* arr, int begin, int end)
{
	if (begin < end)
	{
		int mid = begin+(end-begin) / 2;
		MergeSort(arr, begin, mid);
		MergeSort(arr, mid + 1, end);
		Merge(arr, begin, mid, end);
	}
}


int main()
{
	int arr[] = { 2,3,4,1,7,8,9,5,6 };
	//InsertSort(arr, 9);
	//ShellSort(arr, 9);
	//SelectSort(arr, 9);
	//BubbleSort(arr, 9);
	//QuickSort(arr, 0, 8);
	MergeSort(arr, 0, 8);
	for (int i = 0; i < 9; i++)
	{
		cout << arr[i] << endl;
	}
	return 0;
}